<?php

namespace app\admin\controller\assessment;

use app\common\controller\Backend;
use think\Log;
use think\Db;
require_once(VENDOR_PATH . 'tcpdf/tcpdf.php');

/**
 * 预评报告
 *
 * @icon fa fa-circle-o
 */
class Prereport extends Backend
{
    
    /**
     * Prereport模型对象
     * @var \app\admin\model\assessment\Prereport
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\assessment\Prereport;

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $where1='1=1';
            $total = $this->model
            ->with(['assessmentitems','admin'])
                    ->where($where)
                    ->where($where1)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
            ->with(['assessmentitems','admin'])
                    ->where($where)
                    ->where($where1)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();


            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 获取一个预评的所有版本
     */
    public function versions($item_id){
        //TODO: 权限验证
        $sort='mf_assessment_prereport.id';
        $order='desc';
        $where1='item_id=' . $item_id;
        $total = $this->model
        ->with(['admin'])
                ->where($where1)
                ->order($sort, $order)
                ->count();

        $list = $this->model
        ->with(['admin'])
                ->where($where1)
                ->order($sort, $order)
                ->select();

        // $list = collection($list)->toArray();
        // $result = array("total" => $total, "rows" => $list);
        $this->assign('list',$list);
        return $this->view->fetch();
    }
    /**
     * 添加
     */
    public function add1($ids)
    {
        // var_dump($this->request->get('ids'));die();
        // $itemid = $this->request->request('itemid');
        $itemid=$ids;
        $model = \app\admin\model\assessment\Items::get($itemid);
        if($model==null){
            $this->error('没有评估标的', '');
            return $this->view->fetch();
        }
        //TODO: 权限
        
        if ($this->request->isPost()) {
            // 保存
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $params['prereport_userid']=$this->auth->id;
                $params['prereport_ip']=$this->request->ip();
                $params['prereport_time'] = time();
                $params['has_prereport']=true;
                $params['state'] = 1;
                $params['prereport_state'] = 1;
                if(trim($params['prereport_contents']) != trim($model->prereport_contents)){
                    $newversion = $this->newVersion($params['itemid'],$params['prereport_no'],$params['prereport_time'],$params['prereport_userid']
                        ,$params['prereport_ip'],$params['prereport_contents']);
                    $params['prereport_version']=$newversion;
                }
                $model->allowField(true)->save($params);
                $this->success();
            }   
            else
                $this->error(__('Parameter %s can not be empty', ''));
        }else{
            if($model==null){
                $this->error('没有找到评估标的', '');
                // 防止界面报错
                $model = new \app\admin\model\assessment\Items;
                $model->prereport_no='';
                $model->prereport_appraiser_id=0;
                $prereport_time_str = date('Y-m-d H:i:s',time());  
            }else if($model->has_prereport){
                // 评过了，直接取值
                $prereport_time_str = date('Y-m-d H:i:s',$model->prereport_time); 
            }
            else{
                // TODO: 这里类别需要设置 没评，从模板取值
                // $model_template = \app\admin\model\assessment\Templates::get(['template_typeid'=>1,'cop_id'=>$this->auth->cop_id]);
                $model_template = \app\admin\model\assessment\Templates::get(['template_typeid'=>1]);
                $templates = $model_template->template;
                // 替换
                $str = str_replace('${OBLIGEE}',$model->obligee,$templates);
                if($model->share_id>0){
                    $share_model = \app\admin\model\assessment\Shares::get($model->share_id);
                    if(!empty($share_model)){
                        $str = str_replace('${SHARETYPE}',$share_model->description,$str);    
                    }
                }
                //$str = str_replace('${PREREPORT_NO}','',$str);
                $str = str_replace('${ADDRESS}',$model->address,$str);
                $str = str_replace('${PROPERTY_NUM}',$model->property_num,$str);
                // 用途
                if($model->planpurpose>0){
                    $model_planpurpose = \app\admin\model\house\Planpurpose::get($model->planpurpose);
                    if(!empty($model_planpurpose))
                        $str = str_replace('${PLANPURPOSE}',$model_planpurpose->purpose,$str);
                }
                // 获取结构
                if($model->structure>0){
                    $structure_model = \app\admin\model\house\Structure::get($model->structure);
                    if(!empty($structure_model))
                        $str = str_replace('${STRUCTURE}',$structure_model->structure,$str);
                }
                $str = str_replace('${AGE}',$model->age,$str);
                $str = str_replace('${AREA}',$model->area,$str);
                $str = str_replace('${AREA_ADDITIONAL}',empty($model->area_addtional)?"":$model->area_addtional,$str);
                $str = str_replace('${SHAREAREA}',$model->share_area,$str);
                $str = str_replace('${FLOORCOUNT}',$model->floor_count,$str);
                $str = str_replace('${LOCATION_FLOOR}',$model->location_floor,$str);
                $str = str_replace('${FINISHYEAR}',$model->age,$str);
                $str = str_replace('${RIGHTLIMIT}',$model->right_limit,$str);
                // 取产证类型
                if($model->property_num_type>0){
                    $property_num_type_model = \app\admin\model\assessment\Propertynumtype::get($model->property_num_type);
                    if(!empty($property_num_type_model)){
                        $str = str_replace($str,'{$PROPERTY_NUM_TYPE}',$property_num_type_model->property_num_type);
                    }
                }

                if($model->prereport_time==0)
                    $model->prereport_time=time();
                $prereport_time_str = date('Y-m-d H:i:s',$model->prereport_time);  
                // 权利类型
                if($model->right_typeid>0){
                    $righttype_model=\app\admin\model\assessment\Righttype::get($model->right_typeid);
                    if(!empty($righttype_model)){
                        $str = str_replace('${RIGHTTYPE}',$righttype_model->righttype,$str);
                    }
                }
                // 权利性质
                if($model->landright>0)
                 {   
                     $landright_model=\app\admin\model\house\Landright::get($model->landright);
                    if(!empty($landright_model)){
                        $str = str_replace('${LANDRIGHT}',$landright_model->rights,$str);
                    }
                }

                $str = str_replace('${PICTURES}','',$str);
                $model_cop = \app\admin\model\auth\Cops::get($this->auth->cop_id);
                if(empty($model_cop)){
                    $model_cop = \app\admin\model\auth\Cops::get(1);
                }
                $str = str_replace('${COP_NAME}',$model_cop->cop_name,$str);
                $model->prereport_contents=$str;
                $model_number = new \app\admin\model\auth\Copnumber;
                /// 生成版本号
                if(empty($model->prereport_no)){
                    $year = (int)date("Y");
                    $month = date("m");
                    $no = $model_number->where('cop_id=' . $this->auth->cop_id . ' and year=' . $year)->max('max_number') ;
                    $model_number->max_number=$no+1;
                    $model_number->cop_id = $this->auth->cop_id;
                    $model_number->primary_id = $model->id;
                    $model_number->tablename='mf_assessment_prereport';
                    $model_number->year=$year;
                    $model_number->save();
    
                    $model->prereport_no='W'.$year .'-'.$month .'-'. str_pad($model_number->max_number.'',5,"0",STR_PAD_LEFT);
                    $model->save();
                }
                
                //TODO: 这里要有个规则
                $model->prereport_appraiser_id=0;
                
            }
            $this->assign('row',$model);
        }
        $this->assign('prereport_time_str',$prereport_time_str);
        $this->assign("area",$model->area);
        $this->assign('itemid',$itemid);
        return $this->view->fetch();
    }
    /**
     * 记录该版本
     * 返回新版本号
     */
    public function newVersion($item_id,$prereport_no,$create_time,$create_userid,$create_ip,$contents){
        // 当前最大版本号
        $model = new \app\admin\model\assessment\Prereport;
        $version = $model->where('item_id='.$item_id)->max('version');
        $version++;
        $model=new \app\admin\model\assessment\Prereport;
        $model->item_id=$item_id;
        $model->prereport_no = $prereport_no;
        $model->create_time  = $create_time;
        $model->create_userid= $create_userid;
        $model->create_ip    = $create_ip;
        $model->contents     = $contents;
        $model->version      = $version;
        $model->save();
        return $version;
    }
    /**
     * 在线预览pdf
     */
    public function previewpdf($ids){
        return $this->generatepdf($ids,'I');
    }
    /**
     * 下载pdf
     */
    public function downloadpdf($ids){
        return $this->generatepdf($ids,'D');
    }
    /**
     * 下载pdf
     */
    public function generatepdf($ids,$type){
        $model = \app\admin\model\assessment\Items::get($ids);
        //TODO: 现在就一个公司
        $cop = \app\admin\model\auth\Cops::get($this->auth->cop_id);
        //TODO: 权限要设置
        $picturesModel = new \app\admin\model\assessment\Pictures;
        $pictures = $picturesModel->join('mf_assessment_picturetype','mf_assessment_pictures.typeid=mf_assessment_picturetype.id','left')->where(['item_id'=>$ids])->select();
        // 估价对象照片
        $arrpics=[];
        // 把证书营业执照和证书放进来，这里是需要单独一页放的
        $arrlicence=[];
        foreach($pictures as $key=>$value){
            if(strpos($value->type_name,'产证') !== false)
                $arrlicence[] = ltrim($value->path,'/');    
            else
                $arrpics[] = ltrim($value->path,'/');
        }
        $arrlicence[] = ltrim($cop->certificate,'/');
        $arrlicence[] = ltrim($cop->business_license,'/');
        // 下载地图图片，并放到单独页面中
        $url = "https://api.map.baidu.com/staticimage/v2?ak=pRVt8KGYStgQpGgu9DwW42U3uZRg0amX&center="
            . $model->longitude.",".$model->latitude
            . "&width=600&height=700&zoom=15&1576933237647&dpiType=ph&markers="
            . $model->longitude ."," . $model->latitude
            ;
        $target = $this->auth->id . '_map_temp.png';
        if(file_exists('./uploads/maptemp/' . $target)){
            unlink('./uploads/maptemp/' . $target);
        }
        if(file_exists('./uploads/maptemp/_' . $target)){
            unlink('./uploads/maptemp/_' . $target);
        }
        $res = $this->downloadImage($url,$target);

        // 画个图标上去
        $this->drawIndicate($target);
        $arrlicence[] = 'uploads/maptemp/_'.$target;
        //TODO: 权限控制
        return $this->html2pdf($model->prereport_no ,$model->prereport_contents,$cop,$arrpics,$arrlicence,$type);
    }
    /*
    https://api.map.baidu.com/staticimage/v2?ak=pRVt8KGYStgQpGgu9DwW42U3uZRg0amX&center=117.282699,31.866842&width=600&height=700&zoom=15&1576933237647&markers=117.282699,31.866842&labels=117.282699,31.866842&zoom=15&labelStyles=评估物位置,1,14,0xffffff,0x000fff,1&dpiType=ph
    */
    /**
     * 自定义合并图像方法，如果不用这个图片可能黑底
     */
    private function imagecopymerge_alpha($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct){
        $opacity=$pct;
        // getting the watermark width
        $w = imagesx($src_im);
        // getting the watermark height
        $h = imagesy($src_im);

        // creating a cut resource
        $cut = imagecreatetruecolor($src_w, $src_h);
        // copying that section of the background to the cut
        imagecopy($cut, $dst_im, 0, 0, $dst_x, $dst_y, $src_w, $src_h);
        // inverting the opacity
        $opacity = 100 - $opacity;

        // placing the watermark now
        imagecopy($cut, $src_im, 0, 0, $src_x, $src_y, $src_w, $src_h);
        imagecopymerge($dst_im, $cut, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $opacity);
    }
    /**
     * 画个图标上去
     */
    private function drawIndicate($filename){
        $dst_path = './uploads/maptemp/'.$filename;
        $src_path = './assets/img/indicate.png';
        $dst = imagecreatefromstring(file_get_contents($dst_path));//读取背景图片数据流
        $src = imagecreatefromstring(file_get_contents($src_path));//读取二维码数据流
        //获取水印图片的宽高
        list($src_w, $src_h) = getimagesize($src_path);
        //将水印图片复制到目标图片上，最后个参数100是设置透明度，这里实现不透明效果
        //imagecopymerge($dst, $src, 300, 250, 0, 0, $src_w, $src_h, 40);
        //如果水印图片本身带透明色，则使用imagecopy方法
        //  imagecopy($dst, $src, 300, 250, 0, 0, $src_w, $src_h);
        $this->imagecopymerge_alpha($dst, $src, 300, 250, 0, 0, $src_w, $src_h,0);
        //设置水印文字颜色
        //SIMYOU.TTF 是幼圆字体
        // $col = imagecolorallocatealpha($dst,0,0,0,0);
        // //添加水印文字
        // //30 是字体大小
        // //215横坐标
        // //875 980 是纵坐标
        // imagettftext($dst,30,0,215,875,$col,"SIMYOU.TTF",'AEINK');
        // imagettftext($dst,30,0,215,980,$col,"SIMYOU.TTF",'www.aeink.com');
        //输出图片
        list($dst_w, $dst_h, $dst_type) = getimagesize($dst_path);
        // 保存png
        imagepng($dst,'./uploads/maptemp/_' . $filename);

        //将数据进行销毁
        imagedestroy($dst);
        imagedestroy($src);
    }


    function downloadImage($url, $filename)
    {
        $path='uploads/maptemp/';
        $ch = curl_init(); //curl_init(): 初始化一个新的会话，返回一个cURL句柄，供curl_setopt(), curl_exec()和curl_close() 函数使用。
        curl_setopt($ch, CURLOPT_URL, $url);//curl_setopt(): 设置一个cURL传输选项,
        //CURLOPT_URL: 需要获取的 URL 地址，也可以在curl_init() 初始化会话的时候。
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //CURLOPT_RETURNTRANSFER: TRUE将curl_exec()获取的信息以字符串返回，而不是直接输出。
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);//CURLOPT_CONNECTTIMEOUT: 在尝试连接时等待的秒数。设置为0，则无限等待。
        $file = curl_exec($ch);//curl_exec(): 执行一个cURL会话
        curl_close($ch);//curl_close(): 关闭一个cURL会话
        $this->saveAsImage($url, $file, $path,$filename);
    }

    function saveAsImage($url, $file, $path,$filename)
    {
        // $filename = pathinfo($url, PATHINFO_BASENAME);//pathinfo(): 返回文件路径的信息
        // $filename = 'temp.png';
        $resource = fopen($path . $filename, 'a');//fopen(): 打开文件或url
        fwrite($resource, $file);//fwrite(): 写入文件
        fclose($resource);//fclose(): 关闭一个已经打开的文件指针
        return $filename;
    }

    // public function download()
    // {
    //     $url = 'https://api.map.baidu.com/staticimage/v2?ak=pRVt8KGYStgQpGgu9DwW42U3uZRg0amX&center=117.282699,31.866842&width=600&height=700&zoom=15&1576933237647&markers=117.282699,31.866842&labels=117.282699,31.866842&zoom=15&labelStyles=评估物位置,1,14,0xffffff,0x000fff,1&dpiType=ph';
    //     var_dump($url);die();
    //     $res = $this->downloadImage($url,'temp.png');
    // }
    // public function pdftest($ids){
    //     $model = \app\admin\model\assessment\Items::get($ids);
    //     $pictures=[
    //         'http://148.70.110.25:90/uploads/20191219/f0d142bf8c23912991eff68a5959546f.jpg',
    //         'http://148.70.110.25:90/uploads/20191219/f0d142bf8c23912991eff68a5959546f.jpg',
    //         'http://148.70.110.25:90/uploads/20191219/f0d142bf8c23912991eff68a5959546f.jpg',
    //         'http://148.70.110.25:90/uploads/20191219/f0d142bf8c23912991eff68a5959546f.jpg',
    //         'http://148.70.110.25:90/uploads/20191219/f0d142bf8c23912991eff68a5959546f.jpg',
    //         'http://148.70.110.25:90/uploads/20191219/f0d142bf8c23912991eff68a5959546f.jpg'];

    //     $cop = \app\admin\model\auth\Cops::get(1);
    //     $this->html2pdf('test',$model->prereport_contents,$cop,$pictures,[]);
    // }
    ///TCPDF说明 https://www.cnblogs.com/520fyl/p/5396374.html
    /**
     * 生成pdf
     * @param type | I，默认值，在浏览器中打开；D，点击下载按钮， PDF文件会被下载下来；F，文件会被保存在服务器中；S，PDF会以字符串形式输出；E：PDF以邮件的附件输出
     */
    public function html2pdf($filename,$html,$cop,$pics,$arrlicence,$type){
        $pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

        // // Save
        $pdf->SetCreator(PDF_CREATOR);
        $pdf->SetAuthor($cop->cop_name);
        $pdf->SetTitle($cop->cop_name);
        $pdf->setFooterData(array(0,64,0), array(0,64,128));
        $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
        $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
        $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
        $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
        $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
        $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
        $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
        $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
        $pdf->setImageScale(1.53);
        if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
            require_once(dirname(__FILE__).'/lang/eng.php');
            $pdf->setLanguageArray($l);
        }
        $pdf->setFontSubsetting(true);
        $pdf->SetFont('droidsansfallback','', 12);
        $pdf->AddPage();
        $pdf->setTextShadow(array('enabled'=>true, 'depth_w'=>0.2, 'depth_h'=>0.2, 'color'=>array(196,196,196), 'opacity'=>1, 'blend_mode'=>'Normal'));
        $html_array=explode('${PAGE}',$html);
        foreach($html_array as $key=>$value){
            if($key>0) $pdf->AddPage(); //增加一个页面
            $pdf->writeHTML($value,true,0,true,0);
        }
      
        /// 放图片
        $pics_page_count = 0;
        
        foreach($pics as $key=>$value){
            $relative_page =intval($key/4);
            
            if($key % 4==0) $pdf->AddPage();
            $pdf->setPage(2 + $relative_page);
            $x = ($key % 2) * 100 + 5 ;
            if($key%4<=1){
                $y=26;
            }else{
                $y=138;
            }
            if($relative_page==0) $y += 30;
            //Image($file, $x, $y, $w, $h, $type, $link, $align, $resize, $dpi, $palign, $ismask, $imgmask, $border);
            $pdf->Image($value,$x, $y, 90, 100, '', '', '', false, 300);
            $pics_page_count = $relative_page + 1;
        }
        /// 放营业执照等
        $page = 2 + $pics_page_count;
        foreach($arrlicence as $key=>$value){
            $pdf->AddPage();
            $pdf->setPage($page);
            $x = 12;
            $y = 50;
            $pdf->Image($value,$x, $y, 186, 180, '', '', '', true, 300);
            $page++;
        }
     
        $path=ROOT_PATH.'public/uploads/';
        if(!is_dir($path)){
            mkdir($path,'0777',true);
        }
        $pdf->setPage(1); 
        $pdf->Image(ltrim($cop->stamp_path,'/'), 140, 185, 50, '', '', '', '', false, 300);


        $pdf->Output("{$filename}.pdf", $type);
        $pdf->close();
    }
   
    /**
     * 审核
     */
    public function verify(){
        $ids = $this->request->post('ids');
        $state=$this->request->post('state');
        $model = \app\admin\model\assessment\Items::get($ids);
        if(empty($model)){
            return json(['success'=>false]);
        }
        //TODO: 权限
        $model->prereport_state = $state;
        $model->prereport_verify_userid = $this->auth->id;
        $model->prereport_verify_time = time();
        $model->prereport_verify_ip = $this->request->ip();
        $model->save();
        return json(['success'=>true]);
    }
    /**
     * 使用pandas预测房价
     */
    public function predict($areaCode,$shiCount,$tingCount,$area,$floor,$floorTotal,$typeId,$decorationId,$metroCount,$buildYear,$sellDate){
        // $pythonpath = getenv('PYTHONPATH'); // see if there is current setting
        // $additional = '/root/anaconda3/envs/tensorflow/bin/python'; // the location where the Tensorflow library is installed.
        // if($pythonpath === false){
        //     putenv("PYTHONPATH=$additional");
        // }
        // $cmd = "/root/anaconda3/envs/tensorflow/bin/python /www/wwwroot/ai_forecast_of_house_price/pandas2.py {$areaCode} {$shiCount} {$tingCount} {$area} {$floor} {$floorTotal} {$typeId} {$decorationId} {$metroCount} {$buildYear} {$sellDate} 2>error.txt 2>&1";
        // exec($cmd,$output,$ret);
        // var_dump($output);
        // var_dump($ret);
        // die();
        // $array = explode(',',$output);
        // foreach($array as $value){
        //     Log::info($value);
        // }
        
        // Log::info($output);
        // return json(['success'=>true,'ret'=>$output]);
        $url = "http://127.0.0.1:8009/predict?areaCode=$areaCode&shiCount=$shiCount&tingCount=$tingCount&area=$area&floor=$floor&floorTotal=$floorTotal&typeId=$typeId&decorationId=$decorationId&metroCount=$metroCount&buildYear=$buildYear&sellDate=$sellDate";
        Log::info($url);
        $html = file_get_contents($url);
        Log::info($html);
        return json_decode($html);
        // return $html;
    }
}
